<script lang="ts">
    import {
        EXTDATA_TYPE_CRAWLER,
        EXTDATA_TYPE_GIT,
        GIT_SERV_ATOMGIT,
        GIT_SERV_GITCODE,
        list as list_extdata,
        remove as remove_extdata,
        type ExtDataInfo,
    } from "$lib/api/board/board_extdata";
    import { boardStore } from "$lib/stores/board.svelte";
    import { userStore } from "$lib/stores/user.svelte";
    import { request } from "$lib/utils/request";
    import EditExtDataModal from "./EditExtDataModal.svelte";
    import { listen } from "@tauri-apps/api/event";
    import type { AllNotice } from "$lib/api/notice_type";
    import RemoveModal from "$lib/components/modal/RemoveModal.svelte";
    import type { Store as ToastStore } from "@zag-js/toast";
    import { getContext } from "svelte";

    const toast: ToastStore = getContext("toast");

    let showAddModal = $state(false);
    let hoverExtDataId = $state("");
    let extDataList = $state([] as ExtDataInfo[]);
    let updateExtDataInfo = $state(null as null | ExtDataInfo);
    let removeExtDataInfo = $state(null as null | ExtDataInfo);

    async function loadExtDataList() {
        const res = await request(
            list_extdata({
                session_id: userStore.userSession,
                board_id: boardStore.curBoardId,
            }),
        );
        extDataList = res.ext_data_list;
    }

    loadExtDataList();

    async function removeExtData() {
        if (removeExtDataInfo == null) {
            return;
        }
        await request(
            remove_extdata({
                session_id: userStore.userSession,
                board_id: boardStore.curBoardId,
                ext_data_id: removeExtDataInfo.ext_data_id,
            }),
        );
        toast.create({
            title: "成功",
            description: "删除外部数据源成功!",
            type: "success",
        });
        removeExtDataInfo = null;
    }

    $effect(() => {
        const unListen = listen<AllNotice>("notice", (ev) => {
            const payload = ev.payload;
            if (payload.BoardNotice != undefined) {
                if (
                    payload.BoardNotice.ExtDataConfigChangeNotice !=
                        undefined &&
                    payload.BoardNotice.ExtDataConfigChangeNotice.board_id ==
                        boardStore.curBoardId
                ) {
                    loadExtDataList();
                }
            }
        });
        return () => {
            unListen.then((fn) => fn());
        };
    });
</script>

<div
    class="card border-[1px] border-surface-200-800 w-full p-0 rounded-[10px] bg-surface-100-900"
>
    <header
        class="border-b-[2px] border-surface-200-800 flex justify-between bg-surface-200-800 pl-2 pr-2 rounded-t-[10px]"
    >
        <h4 class="h4">外部数据源列表</h4>
        <div>
            <button
                type="button"
                class="btn preset-filled-primary-900-100 rounded-[10px] h-[30px] mt-[4px]"
                disabled={boardStore.curWebBoard?.myMember?.admin != true}
                onclick={() => (showAddModal = true)}>增加</button
            >
        </div>
    </header>

    <div class="table-wrap">
        <table class="table">
            <thead>
                <tr>
                    <th>名称</th>
                    <th>数据类别</th>
                    <th>数据来源</th>
                    <th>服务地址</th>
                    {#if boardStore.curWebBoard?.myMember?.admin}
                        <th class="w-[120px]">操作</th>
                    {/if}
                </tr>
            </thead>
            <tbody>
                {#each extDataList as extData}
                    <tr
                        class="hover:preset-tonal h-[50px]"
                        onmouseenter={() =>
                            setTimeout(() => {
                                hoverExtDataId = extData.ext_data_id;
                            }, 100)}
                        onmouseleave={() => (hoverExtDataId = "")}
                    >
                        <td>{extData.basic_info.name}</td>
                        <td
                            >{#if extData.basic_info.ext_data_type == EXTDATA_TYPE_GIT}
                                Git数据
                            {:else if extData.basic_info.ext_data_type == EXTDATA_TYPE_CRAWLER}
                                网页数据
                            {/if}
                        </td>
                        <td>
                            {#if extData.basic_info.serv_type.GitServType == GIT_SERV_ATOMGIT}
                                AtomGit
                            {:else if extData.basic_info.serv_type.GitServType == GIT_SERV_GITCODE}
                                GitCode
                            {/if}
                        </td>
                        <td>{extData.basic_info.serv_url}</td>
                        {#if boardStore.curWebBoard?.myMember?.admin == true}
                            <td>
                                <div class="flex gap-2">
                                    <button
                                        type="button"
                                        onclick={() =>
                                            (updateExtDataInfo = extData)}
                                        >修改</button
                                    >
                                    {#if hoverExtDataId == extData.ext_data_id}
                                        <button
                                            type="button"
                                            class="btn preset-filled-error-200-800"
                                            onclick={() =>
                                                (removeExtDataInfo = extData)}
                                            >删除</button
                                        >
                                    {/if}
                                </div>
                            </td>
                        {/if}
                    </tr>
                {/each}
            </tbody>
        </table>
    </div>
</div>

<div class="absolute -left-[10000px]">
    {#if showAddModal}
        <EditExtDataModal onClose={() => (showAddModal = false)} />
    {/if}
    {#if updateExtDataInfo != null}
        <EditExtDataModal
            extDataInfo={updateExtDataInfo}
            onClose={() => (updateExtDataInfo = null)}
        />
    {/if}
    {#if removeExtDataInfo != null}
        <RemoveModal
            title="删除外部数据源"
            content={`是否删除外部数据源 ${removeExtDataInfo.basic_info.name} ?`}
            onCancel={() => (removeExtDataInfo = null)}
            onOk={() => removeExtData()}
        />
    {/if}
</div>
